package snuvm.assemblerARM9;

import snuvm.*;
import snuvm.util.Binary;
import snuvm.arm9.instructions.*;
import java.util.*;

/*
Copyright (c) 2009-2010,  Jeongho Nah, Gangwon Jo, Jaejin Lee

Developed by 
	Jeongho Nah (jeongho"at"aces.snu.ac.kr)
	Gangwon Jo (gangwon"at"aces.snu.ac.kr)
	Jaejin Lee (jlee"at"cse.snu.ac.kr)


Permission is hereby granted to use this version of the code 
under the same terms as MARS, which has the following license:

--
Copyright (c) 2003-2008,  Pete Sanderson and Kenneth Vollmar

Developed by Pete Sanderson (psanderson"at"otterbein.edu)
and Kenneth Vollmar (kenvollmar"at"missouristate.edu)

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject 
to the following conditions:

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR 
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(MIT license, http://www.opensource.org/licenses/mit-license.html)
 */

/**
 * Provides utility method related to MIPS operand formats.
 * 
 * @author Pete Sanderson 
 * @version August 2003
 */


    public class OperandFormat {
   
       private OperandFormat() {
      }
    
   /*
    * Syntax test for correct match in both numbers and types of operands.
    * 
    * @param candidateList List of tokens generated from programmer's MIPS statement.
    * @param spec The (resumably best matched) MIPS instruction.
    * @param errors ErrorList into which any error messages generated here will be added.
    * 
    * @return Returns <tt>true</tt> if the programmer's statement matches the MIPS 
    * specification, else returns <tt>false</tt>.
    */
   
       static boolean tokenOperandMatch(TokenList candidateList, Instruction inst, ErrorList errors) {
         if (!numOperandsCheck(candidateList, inst, errors))
            return false;
         if (!operandTypeCheck(candidateList, inst, errors)) 
            return false;
         return true;
      }
   	
   /*
    * If candidate operator token matches more than one instruction mnemonic, then select 
    * first such Instruction that has an exact operand match.  If none match, 
    * return the first Instruction and let client deal with operand mismatches.  
    */
       static Instruction bestOperandMatch(TokenList tokenList, ArrayList instrMatches) {
         if (instrMatches == null)
            return null;
         if (instrMatches.size() == 1)
            return (Instruction) instrMatches.get(0);
         for (int i=0; i<instrMatches.size(); i++) {
            Instruction potentialMatch = (Instruction) instrMatches.get(i);
            if (tokenOperandMatch(tokenList, potentialMatch, new ErrorList())) 
               return potentialMatch;
         }
         return (Instruction) instrMatches.get(0);
      }
   
   // Simply check to see if numbers of operands are correct and generate error message if not.
       private static boolean numOperandsCheck(TokenList cand, Instruction spec, ErrorList errors) {
         int numOperands = cand.size()-1;
         int reqNumOperands = spec.getTokenList().size()-1;
         Token operator = cand.get(0);
         if (numOperands == reqNumOperands) {
            return true;
         } 
         else if (numOperands < reqNumOperands) {
            String mess = "Too few or incorrectly formatted operands. Expected: "+spec.getExampleFormat();
            generateMessage(operator, mess, errors);
         } 
         else {
            String mess = "Too many or incorrectly formatted operands. Expected: "+spec.getExampleFormat();
            generateMessage(operator, mess, errors);
         }
         return false;
      }
   
   // Generate error message if operand is not of correct type for this operation & operand position
       private static boolean operandTypeCheck(TokenList cand, Instruction spec, ErrorList errors) {
         Token candToken, specToken;
         TokenTypes candType, specType;
         for (int i=1; i<spec.getTokenList().size(); i++) {
            // OK, we've got an operator match, let's check the operands.
            candToken = cand.get(i);
            specToken = spec.getTokenList().get(i);
            candType = candToken.getType();
            specType = specToken.getType();
           // type mismatch is error EXCEPT when spec calls for register number and candidate is
           // register name and register names permitted.  Or if spec calls
           // for integer of specified max bit length and candidate is integer of smaller bit length.
            if (specType == TokenTypes.REGISTER_NUMBER && 
               candType == TokenTypes.REGISTER_NAME && 
               Globals.getSettings().getBareMachineEnabled()) {
               generateMessage(candToken, "Use register number instead of name.  See Settings.", errors);
               return false;
            }
            if (specType == TokenTypes.REGISTER_NUMBER && 
               candType == TokenTypes.REGISTER_NAME && 
               !Globals.getSettings().getBareMachineEnabled())
               continue;
            if ((specType == TokenTypes.INTEGER_12U && candType == TokenTypes.INTEGER_5U) ||
            	(specType == TokenTypes.INTEGER_12U && candType == TokenTypes.INTEGER_8) ||
            	(specType == TokenTypes.INTEGER_8 && candType == TokenTypes.INTEGER_5U) ||
            	(specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_5U) ||
            	(specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_8) ||
            	(specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_12U) ||
            	(specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_5U) ||
            	(specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_8) ||
            	(specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_12U) ||
            	(specType == TokenTypes.INTEGER_25 && candType == TokenTypes.INTEGER_5U) ||
            	(specType == TokenTypes.INTEGER_25 && candType == TokenTypes.INTEGER_12U) ||
            	(specType == TokenTypes.INTEGER_25 && candType == TokenTypes.INTEGER_16U) ||
            	(specType == TokenTypes.INTEGER_25 && candType == TokenTypes.INTEGER_8) ||
            	(specType == TokenTypes.INTEGER_25 && candType == TokenTypes.INTEGER_16) ||
            	(specType == TokenTypes.INTEGER_32 && candType == TokenTypes.INTEGER_5U) ||
            	(specType == TokenTypes.INTEGER_32 && candType == TokenTypes.INTEGER_12U) ||
            	(specType == TokenTypes.INTEGER_32 && candType == TokenTypes.INTEGER_16U) ||
            	(specType == TokenTypes.INTEGER_32 && candType == TokenTypes.INTEGER_8) ||
            	(specType == TokenTypes.INTEGER_32 && candType == TokenTypes.INTEGER_16) ||
            	(specType == TokenTypes.INTEGER_32 && candType == TokenTypes.INTEGER_25))
               continue;
            if (candType == TokenTypes.INTEGER_16U || candType == TokenTypes.INTEGER_16) {
               int temp = Binary.stringToInt(candToken.getValue());
               if (specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_16U &&   
                   temp>=DataTypes.MIN_HALF_VALUE && temp<=DataTypes.MAX_HALF_VALUE) 
                  continue;
               if (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_16 && 
                   temp>=DataTypes.MIN_UHALF_VALUE && temp<=DataTypes.MAX_UHALF_VALUE) 
                  continue;
            }
            
            if ((specType == TokenTypes.INTEGER_5U && candType == TokenTypes.INTEGER_12U) ||
            	(specType == TokenTypes.INTEGER_5U && candType == TokenTypes.INTEGER_16U) ||
            	(specType == TokenTypes.INTEGER_5U && candType == TokenTypes.INTEGER_8) ||
                (specType == TokenTypes.INTEGER_5U && candType == TokenTypes.INTEGER_16) ||
                (specType == TokenTypes.INTEGER_5U && candType == TokenTypes.INTEGER_25) ||
                (specType == TokenTypes.INTEGER_5U && candType == TokenTypes.INTEGER_32) ||
                (specType == TokenTypes.INTEGER_8 && candType == TokenTypes.INTEGER_12U) ||
                (specType == TokenTypes.INTEGER_8 && candType == TokenTypes.INTEGER_16U) ||
                (specType == TokenTypes.INTEGER_8 && candType == TokenTypes.INTEGER_16) ||
                (specType == TokenTypes.INTEGER_8 && candType == TokenTypes.INTEGER_25) ||
                (specType == TokenTypes.INTEGER_8 && candType == TokenTypes.INTEGER_32) ||
                (specType == TokenTypes.INTEGER_12U && candType == TokenTypes.INTEGER_16U) ||
                (specType == TokenTypes.INTEGER_12U && candType == TokenTypes.INTEGER_16) ||
                (specType == TokenTypes.INTEGER_12U && candType == TokenTypes.INTEGER_25) ||
                (specType == TokenTypes.INTEGER_12U && candType == TokenTypes.INTEGER_32) ||
                (specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_16U) ||
                (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_16) ||
                (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_25) ||
                (specType == TokenTypes.INTEGER_16U && candType == TokenTypes.INTEGER_32) ||
                (specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_25) ||
                (specType == TokenTypes.INTEGER_16 && candType == TokenTypes.INTEGER_32)) {
            	generateMessage(candToken, "operand is out of range", errors);
                return false;
            }

            if (candType != specType) {
            	generateMessage(candToken, "operand is of incorrect type: "+candType+"!="+specType, errors);
               //generateMessage(candToken, "operand is of incorrect type", errors);
               return false;
            }
         }
      	
      /********  nice little debugging code to see which operand format 
       ********  the operands for this source code instruction matched.
      	System.out.print("Candidate: ");
      	for (int i=1; i<spec.size(); i++) {
            System.out.print(cand.get(i).getValue()+" ");
      	}
      	System.out.print("Matched Spec: ");
      	for (int i=1; i<spec.size(); i++) {
            System.out.print(spec.get(i).getValue()+" ");
      	}
         System.out.println();
      */
      	
         return true;
      }
   
   // Handy utility for all parse errors...
       private static void generateMessage(Token token, String mess, ErrorList errors) {
         errors.add(new ErrorMessage(token.getSourceARM9program(), token.getSourceLine(), token.getStartPos(),
                                             "\""+token.getValue()+"\": "+mess));
         return;
      }
   
   }
